<template>
  <div class="app-container customer-div">
    <el-alert
            title="请先选择客户，再添加使用材料"
            close-text="知道了"
            type="warning">
    </el-alert>
    <el-form :inline="true" size="mini" label-width="73px" style="margin-top:20px">
      <el-form-item label="客户名称：">
        <el-select
                clearable
                v-model="customer"
                filterable
                remote
                value-key="customerId"
                reserve-keyword
                placeholder="请输入关键词"
                @change="changeCustomer"
                :remote-method="remoteMethod"
                :loading="loading">
          <el-option
                  v-for="item in customerList"
                  :key="item.customerId"
                  :label="item.customerName"
                  :value="item">
          </el-option>
        </el-select>
      </el-form-item>
    </el-form>

    <div><el-button size="small" type="primary" @click="showMaterialDialog('add',null)" :disabled="!customer">新增材料</el-button></div>
    <el-table
            v-loading="materialLoading"
            :data="materialList"
            border
            style="width: 100%; margin-top: 20px">
      <el-table-column
              prop="categoryName"
              label="材料名称">
        <template slot-scope="scope">
          {{scope.row.categoryName}} {{scope.row.brandName}} {{scope.row.goodsSn}}
        </template>
      </el-table-column>
      <el-table-column
              prop="cycleNumber"
              label="每月用量"
              align="center">
      </el-table-column>
      <el-table-column
              prop="cycleDays"
              label="采购周期"
              align="center">
      </el-table-column>
      <el-table-column
              prop="supplierName"
              label="供应商"
              align="center">
      </el-table-column>
      <el-table-column
              prop="remark"
              label="备注"
              align="center">
      </el-table-column>
      <el-table-column
              label="操作"
              align="center">
        <template slot-scope="scope">
          <el-button
                  @click="showMaterialDialog('edit',scope.row)"
                  type="text"
                  size="mini">修改
          </el-button>
          <el-button
                  @click="delMaterial(scope.row)"
                  type="text"
                  size="mini">删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-button size="small" @click="toBalck" style="margin-top:20px;">返回</el-button>
    <div class="pagination-container">
      <el-pagination
              background
              @size-change="handleSizeChangeMaterial"
              @current-change="handleCurrentChangeMaterial"
              layout="total, sizes,prev, pager, next,jumper"
              :current-page.sync="materialParams.pageNum"
              :page-size="materialParams.pageSize"
              :page-sizes="[10,15,20]"
              :total="materialCount">
      </el-pagination>
    </div>
    <!--新增/编辑使用材料-->
    <el-dialog
            :close-on-click-modal="false"
            :title="title4"
            :beforeClose="handleClose4"
            :visible.sync="dialogVisible4"
            width="800px">
      <el-form :model="materialForm" size="mini" label-width="100px" :rules="rules4" ref="materialForm">
        <el-form-item label="客户名称：">
          <el-input v-model="materialForm.customerName"  disabled></el-input>
        </el-form-item>
        <el-form-item label="使用材料：" prop="categoryId">
          <div v-if="materialDialogType!='see'">
            <div style="display: inline-block;vertical-align: text-top">
              <el-select
                      clearable
                      v-model="cutCategory"
                      filterable
                      remote
                      value-key="categoryId"
                      reserve-keyword
                      placeholder="请输入分类关键词"
                      @change="changeCategory"
                      :remote-method="remoteMethod1"
                      :loading="categoriesloading">
                <el-option
                        v-for="item in categoriesList" :key="item.categoryId" :label="item.parentCategoryName+'/'+item.categoryName " :value="item">
                </el-option>
              </el-select>
            </div>
            <div style="display: inline-block;vertical-align: text-top">
              <el-select
                      clearable
                      v-model="cutBrand"
                      filterable
                      remote
                      value-key="brandId"
                      reserve-keyword
                      placeholder="请输入厂家关键词"
                      @change="changeBrandId">
                <el-option
                        v-for="item in bandList" :key="item.brandId" :label="item.brandName" :value="item">
                </el-option>
              </el-select>
            </div>
            <div style="display: inline-block;vertical-align: text-top">
              <el-select
                      clearable
                      v-model="materialForm.goodsSn"
                      filterable
                      remote
                      value-key="goodsSn"
                      reserve-keyword
                      placeholder="请输入牌号关键词">
                <el-option
                        v-for="item in goodsSnList" :key="item.goodsSn" :label="item.goodsSn" :value="item.goodsSn">
                </el-option>
              </el-select>
            </div>
          </div>
          <div v-else>
            <span v-if="materialForm.categoryName !=''">{{materialForm.categoryName}} / </span>
            <span v-if="materialForm.brandName !=''">{{materialForm.brandName}} / </span>
            <span v-if="materialForm.goodsSn !=''">{{materialForm.goodsSn}}</span>
          </div>

        </el-form-item>
        <el-form-item label="月使用量：" >
          <el-select v-model="materialForm.cycleNumber"  placeholder="请选择" clearable :disabled="materialDialogType=='see'">
            <el-option
                    v-for="item in cycleNumberOptionList"
                    :key="item"
                    :label="item"
                    :value="item">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="采购周期：">
          <el-select v-model="materialForm.cycleDays"  placeholder="请选择" clearable :disabled="materialDialogType=='see'">
            <el-option
                    v-for="item in cycleDaysOptionList"
                    :key="item"
                    :label="item"
                    :value="item">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="供应商：" >
          <el-input v-model="materialForm.supplierName" :disabled="materialDialogType=='see'"></el-input>
        </el-form-item>
        <el-form-item label="备注：">
          <el-input v-model="materialForm.remark" type="textarea" :rows="2" :disabled="materialDialogType=='see'" autosize></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer" v-if="materialDialogType!='see'">
          <el-button @click="handleClose4">取 消</el-button>
          <el-button type="primary" @click="handleConfirm4" :loading="btnLoading4">确 定</el-button>
      </span>
      <span slot="footer" class="dialog-footer" v-else>
          <el-button @click="handleClose4">关 闭</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
  import {
    getCustomerOption,
    getGoodsList,
    getCategoriesList,
    getBrandList,
    getGoodsSnList,
    saveMaterial,categoriesLike,brandLike} from '@/api/partner'
    import { mapGetters } from 'vuex'
    const defaultMaterialForm = {
      customerId:'',
      customerName:'',
      categoryId:'',
      categoryName:'',
      brandId:'',
      brandName:'',
      goodsSn:'',
      supplierName:'',
      cycleDays:'',
      cycleNumber:'',
      remark:'',
    };

    export default {
        name: "material",
        data(){
            return{
              customer:null,
              materialParams:{
                type:'all',
                pageNum:1,
                pageSize:10,
                customerId:'',
              },
              materialList:[],
              materialCount:0,
              materialLoading:false,
              title4:'',
              dialogVisible4:false,
              materialForm:JSON.parse(JSON.stringify(defaultMaterialForm)),
              rules4:{
                customerId:[{required: true, message: '请选择客户', trigger: 'change'},],
                categoryId:[{required: true, message: '请选择分类', trigger: 'change'},],
              },
              btnLoading4:false,
              cycleNumberOptionList:['1吨以下','1-5吨','5-10吨','10-20吨','20-40吨','40-80吨','80吨以上'],
              cycleDaysOptionList:['一周1次','两周1次','一月1次','一月2次','一月3次','二月1次','不固定'],
              categoriesList:[],
              bandList : [],
              goodsSnList: [],
              activeTabName:'name0',
              visible:false,
              visible2:false,
              brandType:1,
              goodsSnType:1,
              materialDialogType:'',
              loading:false,
              customerList:[],
              categoriesloading:false,
              brandLoading:false,
              cutCategory:{},
              cutBrand:{},
            }
        },
        created() {
          // this.getCategoriesListData();
        },
        computed: {
          ...mapGetters([
            'name',
            'mobile',
            'userId'
          ]),
        },
        filters: {


        },
        methods:{
            //获取分类列表
           remoteMethod1(query) {
                if(query && query!= ''){
                    this.categoriesloading = true;
                  categoriesLike({keyword:query}).then(response => {
                        this.categoriesList = response;
                        this.categoriesloading = false;
                    }).catch(()=>{
                        this.categoriesloading = false;
                    });
                }
            },
          //切换分类
          changeCategory(e){
            this.materialForm.categoryId = '';
            this.materialForm.categoryName = '';
            this.bandList = [];
            this.goodsSnList = [];
            this.materialForm.brandId = '';
            this.materialForm.brandName = '';
            this.materialForm.goodsSn = '';
            this.cutBrand = {};
            if(e){
              this.materialForm.categoryId = JSON.parse(JSON.stringify(e.categoryId));
              this.materialForm.categoryName = JSON.parse(JSON.stringify(e.categoryName));
            }
            if(this.materialForm.categoryId && this.materialForm.categoryId != ''){
              brandLike({categoryId:this.materialForm.categoryId}).then(response => {
                this.bandList = response;
                this.brandLoading = false;
              }).catch(()=>{
                this.brandLoading = false;
              });
            }
          },

          //切换厂家
          changeBrandId(val){
            this.materialForm.brandName = '';
            this.materialForm.brandId = '';
             if(val){
               this.materialForm.brandName = val.brandName;
               this.materialForm.brandId = val.brandId;
             }
            this.materialForm.goodsSn = '';
            this.goodsSnList = [];
            if(this.materialForm.brandId){
              getGoodsSnList({categoryId:this.materialForm.categoryId,brandId:this.materialForm.brandId}).then((res)=>{
                this.goodsSnList = res;
              })
            }
          },

          //返回
          toBalck(){
            this.$router.go(-1)
          },
          //切换客户
          changeCustomer(item){
            this.materialList=[];
            if(item){
              this.getMaterialList();
            }
          },
          //获取客户列表
          remoteMethod(query) {
            if(query && query!= ''){
              this.loading = true;
              getCustomerOption({keywords:query,chargeId:this.userId}).then(response => {
                this.customerList = response;
                this.loading = false;
              }).catch(()=>{
                this.loading = false;
              });
            }
          },
          //获取客户使用材料
          getMaterialList(){
            this.materialLoading = true;
            this.materialParams.customerId = this.customer.customerId;
            getGoodsList(this.materialParams).then((res)=>{
              this.materialList = res.list;
              this.materialCount = res.count;
              this.materialLoading = false;
            })
          },
          handleSizeChangeMaterial(val){
            this.materialParams.pageNum = 1;
            this.materialParams.pageSize = val;
            this.getMaterialList();
          },
          handleCurrentChangeMaterial(val){
            this.materialParams.pageNum = val;
            this.getMaterialList();
          },

          //显示编辑/新增使用材料
          showMaterialDialog(type,item){
            this.title4 = type == 'add' ? '新增使用材料' : type == 'edit' ? '编辑使用材料' : '查看使用材料';
            this.materialDialogType = type;
            this.dialogVisible4 = true;
            this.cutCategory= {};
            this.cutBrand = {};
            if(type=='add'){
              this.materialForm = JSON.parse(JSON.stringify(defaultMaterialForm));
              this.materialForm.customerId = this.customer.customerId;
              this.materialForm.customerName = this.customer.customerName;
              this.categoriesList = [];
            }else{
              this.materialForm = JSON.parse(JSON.stringify(item));
              if(this.materialForm.categoryId && this.materialForm.categoryId != ''){
                this.cutCategory.categoryId = this.materialForm.categoryId;
                this.cutCategory.categoryName = this.materialForm.categoryName;
                categoriesLike({keyword:this.cutCategory.categoryName}).then(response => {
                    this.categoriesList = response;
                  }).catch(()=>{
                  });
                brandLike({categoryId:this.materialForm.categoryId}).then(response => {
                  this.bandList = response;
                  this.brandLoading = false;
                }).catch(()=>{
                  this.brandLoading = false;
                });
              }
              if(this.materialForm.brandId && this.materialForm.brandId != ''){
                this.cutBrand.brandId = this.materialForm.brandId;
                this.cutBrand.brandName = this.materialForm.brandName;
                getGoodsSnList({categoryId:this.materialForm.categoryId,brandId:this.materialForm.brandId}).then((res)=>{
                  this.goodsSnList = res;
                })
              }

            }
          },

          //关闭客户使用材料
          handleClose4(){
            this.$refs.materialForm.clearValidate();
            this.dialogVisible4 = false;
            this.btnLoading4 = false;
            this.bandList = [];
            this.goodsSnList = [];
            this.activeTabName = 'name0';
            this.visible = false;
            this.visible2 = false;
            this.brandType= 1;
            this.goodsSnType = 1;
          },

          //提交客户使用材料
          handleConfirm4(){
            this.$refs.materialForm.validate((valid) => {
              if (valid) {
                this.btnLoading4 = true;
                saveMaterial(this.materialForm).then(()=>{
                  this.btnLoading4 = false;
                  this.handleClose4();
                  this.getMaterialList()
                }).catch(()=>{
                  this.btnLoading4 = false;
                })
              }
            });
          },

          //删除客户使用材料
          delMaterial(item){
            this.$confirm('确定删除使用材料?', '提示', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning'
            }).then(() => {
              saveMaterial({status:2,ugId:item.ugId,customerId:item.customerId}).then(()=>{
                this.getMaterialList();
                this.$message({
                  type: 'success',
                  message: '删除成功!'
                });
              });
            }).catch(() => {
              this.$message({
                type: 'info',
                message: '已取消删除'
              });
            });
          },

          //获取分类列表
          getCategoriesListData(){
            getCategoriesList().then((res)=>{
              console.log(res)
              this.categoriesList = res;
            })
          },

          //切换牌号输入形式
          changeGoodsSnType(){
            this.goodsSnType = this.goodsSnType == 1 ? 2 : 1 ;
            this.materialForm.goodsSn = '';
          },
          //切换厂家输入形式
          changeBrandType(){
            this.brandType = this.brandType == 1 ? 2 : 1 ;
            if(this.brandType == 2){ //厂家自定义时，牌号也要变为自定义
              this.goodsSnType = 2
            }
            this.materialForm.brandName = '';
            this.materialForm.brandId = '';
            this.materialForm.goodsSn = '';
            this.goodsSnList = [];
          },
        },
    }
</script>

<style scoped lang="scss">
  .category-pane{
    max-height: 250px;
    overflow: auto;
    .pane-item{
      display: -webkit-box; /* OLD - iOS 6-, Safari 3.1-6 */
      display: -moz-box; /* OLD - Firefox 19- (buggy but mostly works) */
      display: -ms-flexbox; /* TWEENER - IE 10 */
      display: -webkit-flex; /* NEW - Chrome */
      display: flex;
      /* 09版 */
      -webkit-box-align: flex-start;
      /* 12版 */
      -webkit-align-items:flex-start;
      -moz-align-items: flex-start;
      -ms-flex-align: flex-start;
      -o-align-items: flex-start;
      align-items:flex-start;
      -webkit-box-pack:flex-start;
      -ms-flex-pack: flex-start;
      justify-content: flex-start;
      margin-top:10px;
      .item-title{
        font-size:14px;
        color:#333;
        font-weight:bold;
        width:30px;
      }
      .item-right{
        width:calc(100% - 30px);
        font-size:12px;
        color:#888;
        .item-span{
          overflow: hidden;
          text-overflow: ellipsis;
          white-space: nowrap;
          display: inline-block;
          line-height: 22px;
          padding:0 5px;
          cursor: pointer;
          margin-right:10px;
        }
      }
    }
  }
</style>
